package lib.operation;

import java.sql.*;
import java.util.Scanner;

/**
 * @author FBI
 * 2022-02-06 18:35
 */


//查找单个图书,通过书名查找
public class Select implements Do{

    @Override
    public void work() {
        System.out.println("=====查找书籍=====");
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入书名");
        String name = sc.nextLine();  //name为所要查找书名

        Select.selectBook(name);
    }



    public static void selectBook(String name) {
        Statement statement = null;
        Connection connection = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/lib", "root", "2506642408");
            statement = connection.createStatement();
            resultSet = statement.executeQuery("select * from book where name = "+"'"+ name + "'");
            if (resultSet != null){
                while (resultSet.next()){
                    System.out.println("书名:"+resultSet.getString("name") + ", 作者:"+resultSet.getString("author")
                            +", 价格:"+resultSet.getString("price")+"元, 类型:"+resultSet.getString("type"));
                }
            }else {
                System.out.println("请输入正确的书名");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
